﻿using AutoMapper;
using B.S.Base.Write.API.Application.Command;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;

namespace B.S.Base.Write.API.Application.CommandHandLer
{
    public class UpdateRoleCommandHandLer : IRequestHandler<UpdateRoleCommand, APIResult<int>>
    {
       private readonly IBaseRepostiy<RoleModel> _roleModel;
        private readonly IMapper _mapper;

        public UpdateRoleCommandHandLer(IBaseRepostiy<RoleModel> _roleModel, IMapper mapper)
        {
           this. _roleModel = _roleModel;
            this._mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
         
            var list = _mapper.Map<RoleModel>(request);
            var query = await _roleModel.GetAll().FirstOrDefaultAsync(x => x.RoleName == request.RoleName && x.RoleId != request.RoleId && x.IsDeleted == false);
            {
                if (query != null)
                {
                    return new APIResult<int>
                    {
                        Code = ResultCode.Fail,
                        Message = "角色重复"
                    };
                }
            }
            list.UpdateUserTime = DateTime.Now;
            await _roleModel.Update(list);
            return new APIResult<int>
            {
                Code = ResultCode.Ok,
                Data = 1,
                Message = "修改成功"
            };
        }
    }
}
